<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :align-center="true" width="50%" :title="`招工面试信息`">
    <el-form
      ref="jobTagsFormRef"
      :rules="rules"
      :disabled="dialogData.isView"
      :model="dialogData"
      label-width="100px"
      label-suffix=" :"
      :hide-required-asterisk="dialogData.isView"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="岗位" prop="jobTitle">
            <el-input v-model="dialogData.jobTitle" placeholder="请选择岗位" disabled maxlength="30" show-word-limit></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="标题" prop="title">
                <el-input v-model="dialogData.title" placeholder="请填写标题" clearable maxlength="30" show-word-limit></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="面试时间" prop="interviewDate">
                <el-date-picker
                  v-model="dialogData.interviewDate"
                  type="datetime"
                  placeholder="请选择面试时间"
                  value-format="YYYY-MM-DD hh:mm:ss"
                  :disabled-date="getDisabledData"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactor">
                <el-input v-model="dialogData.contactor" placeholder="请填写联系人" clearable maxlength="30" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="dialogData.contactPhone" placeholder="请填写联系电话" clearable maxlength="30" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="面试内容">
            <el-input
              style="width: 100%"
              v-model="dialogData.content"
              :autosize="{ minRows: 4 }"
              type="textarea"
              placeholder="请填写面试内容"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="面试地址" prop="address">
            <section class="form-s2" style="align-items: flex-start">
              <div v-if="jobAddressStr.length" class="jobaddress-marker-tip">
                <div class="addr-tag-content">
                  <el-icon style="margin-right: 0.25rem" size="24">
                    <Place />
                  </el-icon>
                  <el-input v-model="dialogData.address" placeholder="面试地址" style="width: 100%" />
                  <el-icon class="addr-close" @click="handleRemoveMarkJobAddress">
                    <CircleClose />
                  </el-icon>
                </div>
              </div>
              <div class="map-search-box">
                <el-input
                  v-model="mapAddressQuery"
                  placeholder="请输入地址查询"
                  :prefix-icon="Search"
                  @keyup.enter="queryCoord"
                />
                <el-button @click="queryCoord" type="primary" :icon="Search">查找</el-button>
                <el-button @click="handleMarkJobAddress" type="primary" :icon="Check">记为工作地址</el-button>
              </div>
              <div id="mcontainer" class="map-box"></div>
            </section>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" v-show="!dialogData.isView" @click="handleSubmit" :loading="btnLoading" :icon="Link">
              发送面试信息
            </el-button>
            <el-button @click="dialogVisible = false" :icon="Close">关闭</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, shallowRef, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Link, Close, Search, Check } from "@element-plus/icons-vue";
import { sendInterview } from "@/api/modules/common/job";
import AMapLoader from "@amap/amap-jsapi-loader";
import { getCoordFromAddress, getAddressFromCoord } from "@/api/modules/common/map";
import saveMsg from "@/views/im/utils/saveMsg.js";
import { MESSAGE_TYPE } from "@/IM/constant";
import { useImStore } from "@/stores/modules/im";
const imStore = useImStore();
console.log(imStore.chatWith);
//页面的数据
interface JobInterviewDialogOption {
  isView: boolean;
  jobTitle: string;
  title: string;
  contactor: string;
  contactPhone: any;
  address: string;
  posX: any;
  posY: any;
  content: string;
  jobId: any;
  interviewDate: string;
  addressLocation: any;
  workerId: string;
  workerIds: any;
}
//提交按钮，避免多次提交
const btnLoading = ref(false);
//弹出框的参数
const dialogVisible = ref(false);
const chooseInvite = row => {
  console.log(row);
  dialogVisible.value = true;
  dialogData.jobTitle = row.title;
  dialogData.jobId = row.id;
};
//当前表单数据在这里初始化
const dialogData = reactive<JobInterviewDialogOption>({
  isView: false,
  jobTitle: "",
  title: "",
  contactor: "",
  contactPhone: "",
  address: "",
  posX: "",
  posY: "",
  content: "",
  jobId: "",
  interviewDate: "",
  addressLocation: "",
  workerId: "",
  workerIds: []
});

const map = shallowRef<any>(null);
const amap = shallowRef<any>(null);
const mapConfig = {
  key: "ffdc25d48476be43db69ee51b49b80e9",
  version: "2.0",
  plugins: ["AMap.DistrictSearch"]
};
const mapInitInfo = {
  viewMode: "2D",
  zoom: 12,
  center: [120.55, 31.34]
};

const initMap = () => {
  AMapLoader.load(mapConfig)
    .then(AMap => {
      map.value = new AMap.Map("mcontainer", mapInitInfo);
      amap.value = AMap;
    })
    .catch(e => console.log(e));
};

//数据较验
const rules = reactive({
  title: [{ required: true, message: "请填写面试标题", trigger: "blur" }],
  contactor: [{ required: true, message: "请填写联系人", trigger: "blur" }],
  contactPhone: [{ required: true, message: "请填写联系电话", trigger: "blur" }],
  address: [{ required: true, message: "请填写详细面试地址", trigger: "blur" }],
  interviewDate: [{ required: true, message: "请选择面试时间", trigger: "change" }]
});

// 提交数据（新增/编辑）
const jobTagsFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  let workerId = "";
  imStore.contacts.map((item: any) => {
    if (item.userId === imStore.chatWith) {
      workerId = item.workerId;
    }
  });
  if (!workerId) {
    ElMessage.error({ message: `该用户未注册工友无法接受面试邀请！` });
    return;
  }
  jobTagsFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      //提交数据
      dialogData.workerId = workerId;
      dialogData.workerIds = [workerId];
      let res = await sendInterview(dialogData);
      if (res.data) {
        ElMessage.success({ message: `面试信息已发送！` });
        const type = "interview";
        let customEvent = "customEvent";
        let customExts = {
          type: type,
          id: res.data
        };
        let options = {
          customEvent,
          customExts
        };
        saveMsg(options, MESSAGE_TYPE.CUSTOM);
        dialogVisible.value = false;
      }
    } catch (error) {
    } finally {
      btnLoading.value = false;
    }
  });
};

const getDisabledData = date => {
  if (new Date(date).getTime() > new Date().getTime()) {
    return false;
  } else {
    return true;
  }
};
const jobAddressStr = ref("");
const jobAddressObject = ref({} as any);
const mapAddressQuery = ref("");
const handleMarkJobAddress = () => {
  if (Object.keys(jobAddressObject.value).length > 0) {
    jobAddressStr.value =
      jobAddressObject.value.addressComponent.province +
      jobAddressObject.value.addressComponent.city +
      jobAddressObject.value.addressComponent.district +
      mapAddressQuery.value;
    dialogData.address = jobAddressStr.value;
    if (dialogData.addressLocation) {
      let coord = dialogData.addressLocation.split(",").map((e: string) => parseFloat(e));
      if (coord) {
        dialogData.posY = coord[0];
        dialogData.posX = coord[1];
      }
      console.log(dialogData);
    } else {
      ElMessage.error("选择的位置需要精确到区域.");
    }
  } else {
    ElMessage.error("请先进行地址查询！");
  }
};

const handleRemoveMarkJobAddress = () => {
  dialogData.address = "";
  jobAddressStr.value = "";
};

const queryCoord = () => {
  getCoordFromAddress(mapAddressQuery.value)
    .then(res => res.json())
    .then((res: any) => {
      dialogData.addressLocation = res.geocodes[0].location;
      getAddressFromCoord(res.geocodes[0].location)
        .then(address => address.json())
        .then((ares: any) => {
          jobAddressObject.value = ares.regeocode;
        });
      res.geocodes.forEach((geo: any, idx: number) => {
        let coord = geo.location.split(",").map((e: string) => parseFloat(e));
        if (idx == 0) {
          map.value!.setCenter(coord);
        }
        let marker = new amap.value!.Marker({
          position: new amap.value!.LngLat(coord[0], coord[1]),
          title: geo.formatted_address,
          draggable: true,
          cursor: "move"
        });
        map.value!.add(marker);
      });
    });
};
//页面参数
defineExpose({
  chooseInvite
});

watch(dialogVisible, n => {
  if (n) {
    initMap();
  }
});
</script>

<style scoped lang="scss">
.exit-interview-box {
  display: flex;
  align-items: center;
  justify-content: space-around;
  height: 40px;
  line-height: 40px;
  font-size: 1.1rem;
  font-weight: 600;
  border: 1px solid var(--el-color-primary-light-5);
  margin: 5px;
  border-radius: 5px;

  span {
    margin: 0 10px;
    // border: 1px solid red;
    flex: 1;
  }

  .el-button {
    // border: 1px solid red;
    width: 80px;
  }
}

#mcontainer {
  width: 100%;
  height: 20rem;
  border-radius: 4px;
  margin-bottom: 15px;
}

.jobaddress-marker-tip {
  width: 100%;
}
.addr-tag-content {
  display: flex;
  align-items: center;
  color: rgb(117, 117, 117);
  font-size: 1.125rem;
  font-weight: bold;
  border: 1px solid white;
  border-radius: 4px;
  margin-bottom: 10px;
  & .el-icon {
    font-size: 1.4rem;
    color: red;
  }
  cursor: default;
  & .addr-close {
    visibility: hidden;
    color: rgb(161, 161, 161);
    margin-left: 0.25rem;
    font-size: 1.125rem;
    cursor: pointer;
    &:hover {
      color: rgb(114, 114, 114);
    }
  }
  &:hover .addr-close {
    visibility: visible;
  }
  &:hover {
    border: 1px solid rgb(221, 221, 221);
    border-radius: 4px;
  }
}

.form-s1 {
  // border: 1px solid green;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: left;
  border-radius: 0.25rem;
  width: 100%;
}
.form-s2 {
  // border: 1px solid blue;
  @extend .form-s1;
}

.map-search-box {
  z-index: 100;
  width: 100%;
  display: flex;
}

.map-box {
  // border: 1px solid green;
  transform: translateY(10px);
}
</style>
